package com.dong.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dong.base.BaseService;
import com.dong.common.CommonResult;
import com.dong.dao.GoodsDao;
import com.dong.entity.Goods;
import com.dong.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodsService extends BaseService {

    private Map<String, String> hasBalance;

    @Reference
    GoodsDao goodsDao;
    @Autowired
    RedisUtil redisUtil;

    public List<Goods> queryAllGoods() {
        return goodsDao.queryAllGoods();
    }

    public void initGoods(int num) {
        List<Goods> goodsList = goodsDao.queryAllGoods();
        hasBalance = new HashMap<>(goodsList.size());
        for (Goods g : goodsList) {
            String id = g.getId();
            redisUtil.set(id, num);
            logger.info("watch redis:" + id + "--" + redisUtil.get(id));
            redisUtil.set("buyList" + id, "");
            hasBalance.put(id, "1");
        }
    }

    public CommonResult buy(String buyer, String id) {
        CommonResult result = new CommonResult();
        //没有库存标志，视为非法请求
        if (!hasBalance.containsKey(id)) {
            result.setErrorCode(CommonResult.ERROR_CODE_FAILED);
            result.setErrorMsg("非法请求！");
            return result;
        }

        if (hasBalance.get(id) == null) {
            logger.error("库存缓存异常！key = " + id);
            result.setErrorCode(CommonResult.ERROR_CODE_FAILED);
            result.setErrorMsg("请求异常！！");
            return result;
        }

        //测试用，每次请求检查一下是否有库存
        if (redisUtil.getInteger(id) > 0) {
            hasBalance.put(id, "1");
        }
        //没有库存了，直接返回失败结果
        if (hasBalance.get(id).equals("0")) {
            result.setErrorCode(CommonResult.ERROR_CODE_FAILED);
            result.setErrorMsg("库存不足！购买失败！");
            logger.error("库存不足！购买失败！");
            return result;
        }

        result = (CommonResult) redisUtil.buy(buyer, id);
        logger.info("errorCode = " + result.getErrorCode());
        if (result.canRetry()) {
            logger.error("retry:buyer = " + buyer + ";id = " + id);
            buy(buyer, id);
        } else if (!result.isSuccess()) {
            hasBalance.put(id, "0");
        }
        return result;
    }
}
